package org.bsc.myfirstapp.server;


import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * 
 * @author softphone
 */
public class DatabaseUtils {
    private static final String JNDI_CONTEXT = "java:comp/env";
    private static String JDBC_DATA_SOURCE = "jdbc/MyDb";

    private DatabaseUtils() {}


	/**
	 *
	 * @param createDb
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		try {
			Context initCtx = new InitialContext();

			Context envCtx = (Context) initCtx.lookup(JNDI_CONTEXT);

			// Look up our data source
			DataSource ds = (DataSource)envCtx.lookup(JDBC_DATA_SOURCE);
			//DataSource ds = (DataSource)initCtx.lookup(JDBC_DATA_SOURCE);
			
			return 	ds.getConnection();


		} catch (NamingException e) {
			e.printStackTrace();
			
			throw new SQLException(e.getMessage());
		}

	}


	/**
	 *
	 * @param conn
	 */
	public static void releaseConnection( Connection conn ) {
		if( null==conn ) {
			//logger.warn( "given connection is null!");
			return;
		}


		try {
			conn.close();
		} catch (SQLException e) {
			//logger.error( "error during close connection!", e );
		}

	}
}
